<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v20;

use app\api\controller\v2\Auth;
use app\common\cachemodel\AppQq;
use app\common\cachemodel\AppWeibo;
use app\common\cachemodel\MiAppleidUser;
use app\common\cachemodel\MiniAppUser;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Wechat;
use app\common\cachemodel\ZlAppleidUser;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\Rectification as RectificationModel;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Cache;
use think\Log;
use think\response\Json;
use XznsTools\cache\CacheManage;

/**个人信息修改接口
 * @title
 * @desc
 * @url
 * @version 2.4.0
 * Class Demo
 * @package app\api\controller\v2
 */
class Info extends Auth
{
    protected $msg;

    /**
     * 获取个人中心数据
     * @return Json
     */
    public function index()
    {
        try
        {
            $data = [];
            $recode = (new Recode())->getRecodeLists($this->user['id'], 1);
            $data['name'] = $recode['name'];
            $data['sex'] = (int)$recode['type'] === 1 ? 1 : 2;
            $data['year'] = (int)$recode['year'];
            $data['month'] = (int)sprintf('%02u', $recode['month']);
            $data['day'] = (int)sprintf('%02u', $recode['day']);
            $data['hour'] = (int)sprintf('%02u', $recode['hour']);
            $data['minute'] = (int)sprintf('%02u', $recode['minute']);
            $data['timezone'] = (int)$recode['timezone'];
            $data['birth_country'] = $recode['birth_country'];
            $data['birth_province'] = $recode['birth_province'];
            $data['birth_city'] = $recode['birth_city'];
            $data['long_deg'] = (int)$recode['long_deg'];
            $data['long_min'] = (int)$recode['long_min'];
            $data['ew'] = (int)$recode['ew'];
            $data['lat_deg'] = (int)$recode['lat_deg'];
            $data['lat_min'] = (int)$recode['lat_min'];
            $data['ns'] = (int)$recode['ns'];
            $data['avatar'] = $recode['avatar'];
            $data['tel'] = '';

            //判断用户是否绑定微信
            $wechat_info = (new Wechat())->getWechatInfo($this->user['id'], 2);
            if ($wechat_info)
            {
                $data['nickname'] = $wechat_info['nickname'];
            } else
            {
                $data['nickname'] = '';
            }
            //判断用户是否绑定了qq
            $qq_info = (new AppQq())->getUserQqInfoFromCache($this->user['id'], 2);
            if ($qq_info)
            {
                $data['qq_name'] = $qq_info['nickname'];
            } else
            {
                $data['qq_name'] = '';
            }
            //判断用户是否绑定了微博
            $wb_info = (new AppWeibo())->getUserWbInfoFromCache($this->user['id'], 2);
            if ($wb_info)
            {
                $data['wb_name'] = $wb_info['nickname'];
            } else
            {
                $data['wb_name'] = '';
            }

            $field = 'id,status';
            //判断用户是否矫正中
            $where = ['uid' => $this->user['id'], 'status' => ['eq', 1]];
            $rectification = (new RectificationModel())
                ->field($field)
                ->where($where)
                ->count('id');

            if ($this->headers['app-type'] === 'ios')
            {
                $data['is_bind_apple'] = (new ZlAppleidUser())->getAppleId($this->user['id']) ? 1 : 0; // 是否绑定苹果ID
            }

            if ($rectification > 0)
            {
                $data['is_rectification'] = 1;
            } else
            {
                $data['is_rectification'] = 0;
            }

        }
        catch (Exception $e)
        {
            return show(config('code.denied'), '用户信息获取失败,请重新登录');
        }

        if ($this->user['tel'])
        {
            $str = substring($this->user['tel'], '-');
            $tel = $str['after'];
            $data['area_code'] = (int)$str['before'] ?: 86;
            $data['tel'] = Util::hidtel($tel, $data['area_code']);
        }

        return show(200, '成功', $data);
    }

    /**
     * 三方绑定
     * @return Json
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    public function bind_third()
    {
        $param = input('param.param');
        $param = $param ? json_decode($param, true) : [];
        $type = input('param.type/d');
        $this->msg = '';
        switch ($type)
        {
            case 1:
                $res = $this->wechat($param);
                break;
            case  2:
                $res = $this->qq($param);
                break;
            case  3:
                $res = $this->weibo($param);
                break;
            case  5:
                $res = $this->appleId($param);
                break;
            default:
                return show(config('code.error'), '未知的账号');
        }
        if ($this->msg)
        {
            return show(config('code.error'), $this->msg);
        }
        return show(200, '绑定成功', ['nickname' => $res]);
    }

    /**
     * 微信登录
     * @param $wechat_user
     * @return string
     * @throws Exception
     */
    protected function wechat($wechat_user)
    {
        //检测用户是否已绑定
        $WechatModel = new Wechat();
        $user_wechat = $WechatModel->getWechatInfo($this->user['id'], 2);
        if ($user_wechat)
        {
            $this->msg = '您已绑定微信';
            return false;
        }
        //验证是否注册过
        $User = (new Wechat())->getWechatInfo($wechat_user['unionid']);
        if ($User)
        {
            $this->msg = '当前微信已被注册';
            return false;
        }
        try
        {
            $wechat_insert = [
                'uid' => $this->user['id'],
                'nickname' => $wechat_user['nickname'] ?? '匿名用户',
                'sex' => $wechat_user['sex'] ?? 2,
                'city' => $wechat_user['city'] ?? '',
                'province' => $wechat_user['province'] ?? '',
                'country' => $wechat_user['country'] ?? '',
                'headimgurl' => $wechat_user['headimgurl'] ?? '',
                'openid' => $wechat_user['openid'],
                'unionid' => $wechat_user['unionid'],
                'create_time' => time(),
                'update_time' => time(),
            ];
            //qq表生成数据
            $WechatModel->SaveData($wechat_insert);

            // 小程序绑定
            $miniUsers = (new MiniAppUser())->where(['unionid' => $wechat_user['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->column('id');
            if ($miniUsers)
            {
                // 更新数据库状态
                (new MiniAppUser())->where(['unionid' => $wechat_user['unionid'], 'status' => 0, 'mini_type' => 'WEAPP'])->update(['uid' => $this->user['id']]);
                // 删除缓存
                foreach ($miniUsers as $mid)
                {
                    CacheManage::getInstance()->setCacheConfig('miniapp.user', $mid)->rmCache();
                }
            }

            return $wechat_user['nickname'];
        }
        catch (Exception $e)
        {
            $this->msg = '微信绑定失败';
        }
        return false;
    }

    /**
     * QQ登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    protected function qq($param)
    {
        //检测用户是否已绑定
        $QqModel = new AppQq();
        $user_qq = $QqModel->getUserQqInfoFromCache($this->user['id'], 2);
        if ($user_qq)
        {
            return $this->msg = '您已绑定qq';
        }
        // 获取用户qq信息
        $qq_user = $QqModel->QqInfo($param);
        // 验证是否注册过
        $User = (new AppQq())->getUserQqInfoFromCache($qq_user['unionid']);
        if ($User)
        {
            $this->msg = '当前qq号已被注册';
            return false;
        }
        try
        {
            $qq_insert = [
                'uid' => $this->user['id'],
                'openid' => $param['openid'],
                'unionid' => $qq_user['unionid'],
                'create_time' => time(),
                'nickname' => $qq_user['nickname'],
                'sex' => $qq_user['sex'],
                'avatar' => $qq_user['figureurl_qq_1'],
            ];
            //qq表生成数据
            (new AppQq())->SaveData($qq_insert);
            return $qq_user['nickname'];
        }
        catch (Exception $e)
        {
            $this->msg = 'qq绑定失败';
        }
        return false;
    }

    /**
     * 微博登录
     * @param $param
     * @return string
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    protected function weibo($param)
    {
        $WbModel = new AppWeibo();
        //检测用户是否已绑定微博
        $user_wb = $WbModel->getUserWbInfoFromCache($this->user['id'], 2);
        if ($user_wb)
        {
            $this->msg = '您已绑定微博';
            return false;
        }
        // 获取weibo信息
        $wb_user = $WbModel->WeiboInfo($param);
        // 验证当前微博是否注册过
        $User = (new AppWeibo())->getUserWbInfoFromCache($param['uid']);
        if ($User)
        {
            $this->msg = '当前微博已被注册';
            return false;
        }
        try
        {
            $wb_insert = [
                'uid' => $this->user['id'],
                'wbuid' => $param['uid'],
                'create_time' => time(),
                'nickname' => $wb_user['name'],
                'sex' => $wb_user['sex'],
                'avatar' => $wb_user['profile_image_url'],
            ];
            //wb表生成数据
            (new AppWeibo())->SaveData($wb_insert);
            return $wb_user['name'];
        }
        catch (Exception $e)
        {
            $this->msg = '微博绑定失败';
        }
        return false;
    }

    /**
     * 苹果绑定
     * @param $param
     * @return false|string
     * @throws ApiException
     * @throws \think\Exception
     */
    protected function appleId($param)
    {
        $dbModel = new ZlAppleidUser();
        if ((new ZlAppleidUser())->getAppleId($this->user['id']))
        {
            $this->msg = '您已绑定Apple ID';
            return false;
        }
        if (!isset($param['apple_id']))
        {
            $this->msg = '请求异常；绑定失败';
            return false;
        }
        // 验证是绑定
        $user = $dbModel->getUserInfo($param['apple_id']);
        if ($user)
        {
            if ($user['uid'] != $this->user['id'])
            {
                $this->msg = '该Apple ID已绑定其他账号';
                return false;
            } else
            {
                $cacheKey = 'user:has_bind:apple_id:' . $this->user['id'];
                Cache::rm($cacheKey);
                return '已绑定';
            }
        }

        try
        {
            $userData = [
                'apple_id' => $param['apple_id'] ?? '',
                'nickname' => $param['name'] ?? '',
                'email' => $param['email'] ?? '',
                'uid' => (int)$this->user['id'],
                'create_time' => time()
            ];
            // 写入apple信息
            (new ZlAppleidUser())->isUpdate(false)->allowField(true)->save($userData);
            $cacheKey = 'user:has_bind:apple_id:' . $this->user['id'];
            Cache::rm($cacheKey);
            return '已绑定';
        }
        catch (\Exception $e)
        {
            Log::write('绑定苹果异常:' . $e->getMessage(), 'error', true);
            $this->msg = '服务异常；绑定失败';
            return false;
        }
    }

    /**
     * 三方解绑
     * @return Json
     * @throws Exception
     */
    public function ubind_third()
    {
        $type = input('param.type/d');
        $this->msg = '';
        //若用户其他无绑定则不允许解绑
        switch ($type)
        {
            case 1:
                if (!$this->user['tel'])
                {
                    //判断用户是否绑定了qq
                    $qq_info = (new AppQq())->getUserQqInfoFromCache($this->user['id'], 2);
                    if (!$qq_info)
                    {
                        //判断用户是否绑定了微博
                        $wb_info = (new AppWeibo())->getUserWbInfoFromCache($this->user['id'], 2);
                        if (!$wb_info)
                        {
                            if (!(new ZlAppleidUser())->getAppleId($this->user['id']))
                            {
                                return show(config('code.error'), '解绑失败');
                            }
                        }
                    }
                }
                (new Wechat())->DelData($this->user['id']);
                // 微信小程序解绑
                $miniUsers = (new MiniAppUser())->where(['uid' => $this->user['id'], 'status' => 0, 'mini_type' => 'WEAPP'])->column('id');
                if ($miniUsers)
                {
                    // 更新数据库状态
                    (new MiniAppUser())->where(['uid' => $this->user['id'], 'status' => 0, 'mini_type' => 'WEAPP'])->update(['uid' => 0, 'access_token' => '', 'expires_in' => 0]);
                    // 删除缓存
                    foreach ($miniUsers as $mid)
                    {
                        CacheManage::getInstance()->setCacheConfig('miniapp.user', $mid)->rmCache();
                    }
                }
                break;
            case  2:
                if (!$this->user['tel'])
                {
                    //判断用户是否绑定微信
                    $wechat_info = (new Wechat())->getWechatInfo($this->user['id'], 2);
                    if (!$wechat_info)
                    {
                        //判断用户是否绑定了微博
                        $wb_info = (new AppWeibo())->getUserWbInfoFromCache($this->user['id'], 2);
                        if (!$wb_info)
                        {
                            if (!(new ZlAppleidUser())->getAppleId($this->user['id']))
                            {
                                return show(config('code.error'), '解绑失败');
                            }
                        }
                    }
                }
                (new AppQq())->DelData($this->user['id']);
                break;
            case  3:
                if (!$this->user['tel'])
                {
                    //判断用户是否绑定微信
                    $wechat_info = (new Wechat())->getWechatInfo($this->user['id'], 2);
                    if (!$wechat_info)
                    {
                        //判断用户是否绑定了qq
                        $qq_info = (new AppQq())->getUserQqInfoFromCache($this->user['id'], 2);
                        if (!$qq_info)
                        {
                            if (!(new ZlAppleidUser())->getAppleId($this->user['id']))
                            {
                                return show(config('code.error'), '解绑失败');
                            }
                        }
                    }
                }
                (new AppWeibo())->DelData($this->user['id']);
                break;
            case  5:
                if (!$this->user['tel'])
                {
                    //判断用户是否绑定微信
                    $wechat_info = (new Wechat())->getWechatInfo($this->user['id'], 2);
                    if (!$wechat_info)
                    {
                        //判断用户是否绑定了qq
                        $qq_info = (new AppQq())->getUserQqInfoFromCache($this->user['id'], 2);
                        if (!$qq_info)
                        {
                            //判断用户是否绑定了微博
                            $wb_info = (new AppWeibo())->getUserWbInfoFromCache($this->user['id'], 2);
                            if (!$wb_info)
                            {
                                return show(config('code.error'), '解绑失败');
                            }
                        }
                    }
                }
                (new ZlAppleidUser())->DelData((int)$this->user['id']);
                break;
            default:
                return show(config('code.error'), '未知的账号');
        }
        if ($this->msg)
        {
            return show(config('code.error'), $this->msg);
        }
        return show(config('code.success'), '解绑成功');
    }
}
